//index.js
// src: "https://api.bshlsqs.com/statics/xiaochengxu"
//获取应用实例
const app = getApp()

Page({
  data: {
    icon: '../image/icon.png',
    code: '',
    rawData: '',
    encryptedData: '',
    iv: '',
    signature: '',
    city: ""
  },

  //事件处理函数   

  onLoad: function(options) {
    console.log(options)
    if (options && options.city) {
      this.setData({
        city: options.city
      })
    }
    
    let that = this;
    wx.login({
      success(res) {
        that.setData({
          code: res.code
        })

        wx.getUserInfo({
          success(res) {
            that.setData({
              rawData: res.rawData,
              encryptedData: res.encryptedData,
              iv: res.iv,
              signature: res.signature,
            })

            wx.request({
              url: 'https://api.bshlsqs.com/passport/wxlogin',
              data: {
                code: that.data.code,
                rawData: that.data.rawData,
                encryptedData: that.data.encryptedData,
                iv: that.data.iv,
                signature: that.data.signature,
              },
              success(res) {
                // console.log(res)
                that.submitSuccess(res)
              }
            })
          }
        })
      }
    })
  },

  submitSuccess(res) {
    let that = this;
    if(res.data.code == 0) {
      let uid = res.data.data.uid;
      let invite_code = res.data.data.invite_code;

      wx.setStorage({
        key: 'uid',
        data: uid,
      })

      wx.setStorage({
        key: 'invite_code',
        data: invite_code,
      })
      wx.showToast({
        title: '登录成功',
        icon: 'success',
        duration: 2000
      })

      setTimeout(() => {
        wx.navigateTo({
          url: `../center/center?city=${that.data.city}`,
        })
      }, 2 * 1000)
    } else {
      wx.showToast({
        title: res.data.msg,
        icon: 'success',
        duration: 2000
      })
    }
  },

  // 授权登录
  getUserInfoFun() {
    let that = this;
    wx.getUserInfo({
      success(res) {
        console.log(res)
        that.setData({
          rawData: res.rawData,
          encryptedData: res.encryptedData,
          iv: res.iv,
          signature: res.signature,
        })

        wx.request({
          url: 'https://api.bshlsqs.com/passport/wxlogin',
          data: {
            code: that.data.code,
            rawData: that.data.rawData,
            encryptedData: that.data.encryptedData,
            iv: that.data.iv,
            signature: that.data.signature,
          },
          success(res) {
            that.submitSuccess(res)
          }
        })
      }
    })
  },
})